<?php

namespace App\Api\Controllers\v1;

use App\Admin\Helper;
use App\Api\Models\Config;
use App\Http\Controllers\ApiController;
use App\Http\Response\ApiResponse;
use App\Models\Article;
use App\Models\Banner;
use App\Models\Business;
use App\Models\CarBrand;
use App\Models\Money;
use App\Models\News;
use App\Models\PaymentOrder;
use App\Models\Service;
use App\Models\ServiceCategory;
use App\Models\BusinessCategory;
use App\Models\ShopUser;
use App\Models\UserCard;
use App\Models\Worker;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use hg\apidoc\annotation as Apidoc;

/**
 * 常规接口
 * @Apidoc\Group("common")
 * @Apidoc\Sort(1)
 */
class CommonController  extends ApiController
{

    /**
     * NotParse
     * @return mixed
     */
    public function notify(): mixed
    {
        $type = $this->request->route("type");
        return PaymentOrder::notify($type);
    }


    /**
     * 首页接口
     * @Apidoc\Url("/api/v1/common/index")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("banners", type="array", desc="顶部轮播图信息")
     * @Apidoc\Returned("items", type="array", desc="中部轮播图信息")
     * @Apidoc\Returned("news", type="array", desc="公告信息")
     * @Apidoc\Returned("articles", type="array", desc="文章信息")
     */
    public function index(): ApiResponse
    {
        $data['banners'] = Banner::getList();
        foreach ($data['banners'] as $banner){
            $banner->image = cdn_url($banner->image);
        }
        $data['items'] = Banner::getList(1);
        foreach ($data['items'] as $banner){
            $banner->image = cdn_url($banner->image);
        }
        $data['news'] = News::getList();
        $data['articles'] = Article::getList();
        foreach ($data['articles'] as $article){
            $article->image = cdn_url($article->image);
        }
        return $this->response()->data($data);
    }


    /**
     * 文章详情
     * @Apidoc\Url("/api/v1/common/article")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("id", type="int", require="true", desc="文章ID")
     * @Apidoc\Returned("item", type="object", desc="文章详情")
     */
    public function article(): ApiResponse
    {
        $id = $this->request->get("id",0);
        $article = Article::getDetail($id);
        if ($article){
            $article->image = cdn_url($article->image);
        }
        $data['item'] = $article;
        return $this->response()->success("ok")->data($data);
    }


    /**
     * 获取车辆品牌列表
     * @Apidoc\Url("/api/v1/common/brands")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("items", type="array", desc="车辆品牌列表")
     */
    public function brands(): ApiResponse
    {
        $data['items'] = CarBrand::getList();
        return $this->response()->data($data);
    }

    /**
     * 获取车辆类型,车辆颜色 列表
     * @Apidoc\Url("/api/v1/common/typeColor")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("types", type="array", desc="车辆类型列表")
     * @Apidoc\Returned("colors", type="array", desc="车辆颜色列表")
     */
    public function typeColor(): ApiResponse
    {
        $data['types'] = CarBrand::getTypes();
        $data['colors'] = CarBrand::getColors();
        return $this->response()->data($data);
    }


    /**
     * 服务分类列表-改
     * @Apidoc\Url("/api/v1/common/serviceCategory")
     * @Apidoc\Query("shop_id", type="int", desc="门店ID")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned(ref="listItems")
     */
    public function serviceCategory(): ApiResponse
    {
        $shop_id = $this->request->input("shop_id",0);
        $data['items'] = ServiceCategory::getList($shop_id);
        return $this->response()->data($data);
    }

    /**
     * 获取服务列表
     * @Apidoc\Url("/api/v1/common/services")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("shop_id",type="int", require=true, desc="门店ID")
     * @Apidoc\Query("cid",type="int", require=true, desc="分类ID")
     * @Apidoc\Query(ref="queryPage")
     * @Apidoc\Returned(ref="listResult")
     */
    public function services(): ApiResponse
    {
        $data = Service::getList();
        return $this->response()->data($data);
    }

    /**
     * 获取服务详情
     * @Apidoc\Url("/api/v1/common/getService")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("id",type="int", require=true, desc="服务ID")
     * @Apidoc\Returned("detail",desc="服务详情")
     */
    public function getService(): ApiResponse
    {
        $data['detail'] = Service::query()
            ->where("id",$this->request->get("id",0))
            ->first();
        if ($data['detail']){
            $data['detail']->image = cdn_url($data['detail']->image);
        }
        return $this->response()->data($data);
    }

    /**
     * 获取充值页面数据
     * @Apidoc\Url("/api/v1/common/moneys")
     * @Apidoc\Method("GET")
     * @Apidoc\Query(ref="queryLongLat")
     * @Apidoc\Returned(ref="listItems")
     * @Apidoc\Returned("rules", type="array", desc="充值规则描述")
     */
    public function moneys(): ApiResponse
    {
        $data = Money::getData();
        return $this->response()->data($data);
    }

    /**
     * 合作商分类列表
     * @Apidoc\Url("/api/v1/common/businessCategory")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned(ref="listItems")
     */
    public function businessCategory(): ApiResponse
    {
        $list = BusinessCategory::getList();
        $data['items'] = array_merge([['id'=>0,'name'=>'全部']],$list->toArray());
        return $this->response()->data($data);
    }

    /**
     * 获取合作商列表
     * @Apidoc\Url("/api/v1/common/businessList")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("cid",type="int", require=true, desc="分类ID", default="0")
     * @Apidoc\Query("keyword",type="string", require=true, desc="关键词搜索")
     * @Apidoc\Query(ref="queryLongLat")
     * @Apidoc\Query(ref="queryPage")
     * @Apidoc\Returned(ref="listResult")
     */
    public function businessList(): ApiResponse
    {
        $data = Business::getList();
        return $this->response()->data($data);
    }

    /**
     * 获取地图上门店信息
     * @Apidoc\Url("/api/v1/common/getShops")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("limit",type="int", require=false, desc="限制距离单位公里,默认10千米内",default="10")
     * @Apidoc\Query(ref="queryLongLat")
     * @Apidoc\Returned("shops", type="array", desc="门店列表")
     * @Apidoc\Returned("shop_count", type="int", desc="门店数量")
     * @Apidoc\Returned("worker_count", type="int", desc="师傅数量")
     * @Apidoc\Returned("address", type="string", desc="详细地址")
     */
    public function getShops(): ApiResponse
    {
        $data = ShopUser::getShops();
        return $this->response()->data($data);

    }


    /**
     * 门店店铺详情-改 加上 user_card_count 字段 卡包数量
     * @Apidoc\Url("/api/v1/common/shop/:id")
     * @Apidoc\Method("GET")
     * @Apidoc\RouteParam("id",type="int", require=true, desc="门店ID")
     * @Apidoc\Returned("shop", type="object", desc="门店店铺详情")
     */
    public function shop(Request $request): ApiResponse
    {
        $shop_id = $request->route("id",0);
        $shop_id = $shop_id?:$this->shop_id;
        $shop = ShopUser::whereId($shop_id)->with(['workers'=>function($query){
            $query->where("status",0);
        }])->first();
        if ($shop){
            $shop->images = cdn_url($shop->images);
            $shop['workers'] = Helper::workers($shop->workers);
            $shop['categoryList'] = ServiceCategory::getList($shop_id);
            $user_id = $this->user_id;
            $shop['user_card_count'] = 0;
            if ($user_id){
                $shop['user_card_count']  = UserCard::query()
                    ->where("user_id",$user_id)
                    ->where("number",">",0)
                    ->whereDate("start_time","<=",now())
                    ->whereDate("end_time",">=",now())
                    ->count();
            }

        }
        $data['shop'] = $shop;
        return $this->response()->data($data);
    }

    /**
     * 获取师傅列表
     * @Apidoc\Url("/api/v1/common/workers")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("limit",type="int", require=false, desc="限制距离单位公里,默认10千米内",default="10")
     * @Apidoc\Query(ref="queryLongLat")
     * @Apidoc\Returned("shops", type="array", desc="门店师傅列表")
     */
    public function workers(): ApiResponse
    {
        $data = Worker::getShops();
        return $this->response()->data($data);
    }

    /**
     * 获取加盟合作的内容详情
     * @Apidoc\Url("/api/v1/common/joinText")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("content", type="string", desc="内容详情")
     */
    public function joinText(): ApiResponse
    {
        $config = Config::getName("join_text");
        $data['content'] = $config?json_decode($config,true):[];
        return $this->response()->data($data);
    }


    /**
     * 文件上传接口
     * @Apidoc\Url("/api/v1/common/upload")
     * @Apidoc\Method("POST")
     * @Apidoc\ParamType("formdata")
     * @Apidoc\Param("file",type="file", require=true, desc="媒体文件流")
     * @Apidoc\Returned("path", type="string", desc="文件相对路径")
     * @Apidoc\Returned("url", type="string", desc="文件访问路径")
     */
    public function upload(): ApiResponse
    {
        $max = 50*1024;
        $validator = Validator::make(request()->file(),[
            'file' => "file|max:{$max}|mimes:jpeg,png,jpg,mp4",
        ],[
            'file.file' => '请确认你的文件格式',
            'file.max' => '文件最大上传大小为50M',
            'file.mimes' => '请确认上传为jpg,jpeg,png的格式图片或者mp4视频',
        ]);
        if ($validator->fails()) {//如果有错误
            $errors = $validator->errors();
            return $this->response()->error($errors->first());
        }
        $file = request()->file("file");
        $filePath = "wechat/".date('Ymd');
        $disk = Storage::disk(config("admin.upload.disk"));
        $name = "mini-program-".date("His").'_'.Str::random().".png";
        $fileName = $filePath.DIRECTORY_SEPARATOR.$name;
        $res = $disk->put($fileName,$file->getContent());
        if($res) {
            return $this->response()->success("上传成功")->data(['path'=>$fileName,'url'=>cdn_url($fileName)]);
        } else {
            return $this->response()->error("上传失败");
        }
    }
}
